//
//  IndexViewController.m
//  HuateVideo
//
//  Created by Tiger on 12-5-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "IndexViewController.h"
#import "SBJSON.h"
#import <QuartzCore/QuartzCore.h>
#import "DetailViewController.h"
#import "SearchViewController.h"
#import "CommonWebServices.h"
#import "TJSP.h"
#import "DataList.h"
#import "AppDelegate.h"
#import "PicShowViewController.h"

@interface IndexViewController ()

@end

@implementation IndexViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        sectionTagArray=[[NSMutableArray alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [sectionTagArray release];
    [table release];
    [channelArray release];
    [scroll release];
    [pageControl release];
    [topTitle release];
    [tableHeaderView release];
    
    [array0 release];
    [array1 release];
    [array2 release];
    [array3 release];
    [array4 release];
    [array5 release];
    [array6 release];
    [array7 release];
    [array release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.view.backgroundColor = TOOLBAR_TINTCOLOR;
    currentPage = 0;
    
    array0 = [[NSMutableArray alloc]init];
    array1 = [[NSMutableArray alloc]init];
    array2 = [[NSMutableArray alloc]init];
    array3 = [[NSMutableArray alloc]init];
    array4 = [[NSMutableArray alloc]init];
    array5 = [[NSMutableArray alloc]init];
    array6 = [[NSMutableArray alloc]init];
    array7 = [[NSMutableArray alloc]init];
    array = [[NSMutableArray alloc]init];
    
    NSString *path = [[NSBundle mainBundle]pathForResource: @"Channels" ofType: @"json"];
    NSString *channelListStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    SBJSON *json = [[SBJSON new] autorelease];
    channelArray = [[NSMutableArray alloc]initWithArray:[json objectWithString:channelListStr error:nil]];
    
    NSNumber* num=[NSNumber numberWithInt:0];
    for (NSObject*o in channelArray) {
         [sectionTagArray addObject:num];
    }
    [self initNavItems];
    
    [self loadData];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void)loadData
{
    CommonWebServices *webServ = [[CommonWebServices alloc] init];
    webServ.delegate = self;
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    [parma setValue:@"0" forKey:@"Nodeid"];
    [webServ startRequestWithMode:@"Default" Action:@"GetTJW" Parma:parma Class:@"DataList" RootXML:@"GetTJWResult" resultIsArray:YES];
    [webServ release];
}

#pragma mark - CommonWebServicesDelegate

- (void)onCommonWebServicesWithCustomClass:(id)object {
    if (object) {
        NSArray *list = [[NSArray alloc]initWithArray:((DataList *)object).List];
        
        if ([list count]>0) {
            for (int i=0; i<[list count]; i++) {
                TJSP *delePlay = [list objectAtIndex:i];
                
                if ([delePlay.Type intValue] == MovieChannelTypeHot) {
                    [array0 addObject:delePlay];
                }
                else if ([delePlay.Type intValue] == MovieChannelTypeMovie) {
                    [array1 addObject:delePlay];
                }
                else if ([delePlay.Type intValue] == MovieChannelTypeSeries) {
                    [array2 addObject:delePlay];
                }
                else if ([delePlay.Type intValue] == MovieChannelTypeMicroViedo) {
                    [array3 addObject:delePlay];
                }
                else if ([delePlay.Type intValue] == MovieChannelTypeMusic) {
                    [array4 addObject:delePlay];
                }
                else if ([delePlay.Type intValue] == MovieChannelTypePic) {
                    [array5 addObject:delePlay];
                }
                else if ([delePlay.Type intValue] == MovieChannelTypeNews) {
                    [array6 addObject:delePlay];
                }
                else if ([delePlay.Type intValue] == MovieChannelTypeOriginal) {
                    [array7 addObject:delePlay];
                }
            }
            
            [array addObject:array1];
            [array addObject:array2];
            [array addObject:array3];
            [array addObject:array4];
            [array addObject:array5];
            [array addObject:array6];
            [array addObject:array7];
            
            count = [array0 count];
            if (count>0) {
                [UserDefaults setObject:array0 forKey:@"TJLB"];
                [self initTableView];
                
            }
        }
    }
    
    [self deleteLoading];
}

- (void)onCommonWebServicesFaild
{
    UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"加载失败")  
                                                        message:LS(@"请检查网络连接和设置")
                                                       delegate:self 	
                                              cancelButtonTitle:LS(@"确定")
                                              otherButtonTitles:nil];		
    [alertview show];		
    [alertview release];
    
    
    [self deleteLoading];
}

- (void)deleteLoading
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [delegate deleteDefaultImage];
}

#pragma mark userMethods
-(void)initNavItems{
    UIImageView* logoImg=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];    
    UIBarButtonItem* logobarItem=[[UIBarButtonItem alloc] initWithCustomView:logoImg];
    self.navigationItem.leftBarButtonItem=logobarItem;
    [logoImg release];
    [logobarItem release];
    
    UIButton *searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame=CGRectMake(0, 0, 42, 31);
    [searchBtn setImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(pushSearchView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* searchBarItem=[[UIBarButtonItem alloc] initWithCustomView:searchBtn];    
    self.navigationItem.rightBarButtonItem=searchBarItem;
    [searchBarItem release];
}

-(void)initTableView{
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 367)];
    table.delegate = self;
    table.dataSource = self;
    scroll.tag = 10000;
    table.allowsSelection = NO;
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    table.backgroundColor = self.view.backgroundColor;
    [self.view addSubview:table];
    
    tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 160)];
    tableHeaderView.backgroundColor = [UIColor clearColor];
    table.tableHeaderView = tableHeaderView;
    
    if (array0.count>0) {
        [self initTopView];
    }
    
}

- (void)turnScrollPage
{
    currentPage++;
    if (currentPage == count) {
        currentPage = 0;
    }
    [UIView beginAnimations: nil context:nil];
    [UIView setAnimationDuration: 0.5];
    [scroll setContentOffset:CGPointMake(currentPage*320, 0) animated:YES];
    [UIView commitAnimations];
}

- (void)initTopView
{
    scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 160)];
    scroll.backgroundColor = [UIColor clearColor];
    scroll.contentSize = CGSizeMake(320*count, 160);
    scroll.showsVerticalScrollIndicator = NO;
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.tag = 10001;
    scroll.pagingEnabled = YES;
    scroll.delegate = self;
    [tableHeaderView addSubview:scroll];
    
    UIView *pageView = [[UIView alloc]initWithFrame:CGRectMake(0, 120, 320, 40)];
    pageView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    [tableHeaderView addSubview:pageView];
    [pageView release];
    
    TJSP *delePlay = [array0 objectAtIndex:0];
    
    topTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 3, 320, 20)];
    topTitle.backgroundColor = [UIColor clearColor];
    topTitle.text = delePlay.News_title;
    topTitle.textColor = [UIColor whiteColor];
    topTitle.font = [UIFont systemFontOfSize:15.0];
    topTitle.textAlignment = UITextAlignmentCenter;
    [pageView addSubview:topTitle];
    
    pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 20, 320, 20)];
    pageControl.userInteractionEnabled = NO;
    pageControl.numberOfPages = count;
    pageControl.selected = 0;
    pageControl.backgroundColor = [UIColor clearColor];
    [pageView addSubview:pageControl];
    
    for (int i=0; i<count; i++) {
        UIButton *topImage = [UIButton buttonWithType:UIButtonTypeCustom];
        topImage.frame = CGRectMake(320*i, 0, 320, 160);
        topImage.tag = 20000+i;
        [topImage addTarget:self action:@selector(toDetailViewController:) forControlEvents:UIControlEventTouchUpInside];
        [topImage setBackgroundImage:[UIImage imageNamed:@"topImage.png"] forState:UIControlStateNormal];
        [scroll addSubview:topImage];
        
        TJSP *delePlay = [array0 objectAtIndex:i];
        
        if (!delePlay.iconImg && !delePlay.isImageLoading) {
            delePlay.isImageLoading = YES;
            [array0 replaceObjectAtIndex:i withObject:delePlay];
            
            ImageDownloader* imageDown = [[ImageDownloader alloc] init];
            imageDown.imageURL = delePlay.News_pic;
            imageDown.delegate = self;
            imageDown.tag = 20000+i;
            [imageDown startDownload:YES];
            [imageDown release];
        }
        else if (delePlay.iconImg) {
            [topImage setBackgroundImage:delePlay.iconImg forState:UIControlStateNormal];
        }
    }
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 
                                                      target:self 
                                                    selector:@selector(turnScrollPage) 
                                                    userInfo:nil 
                                                     repeats:YES];
    [timer retain];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.tag == 10001) {
        CGPoint p = scrollView.contentOffset;
        currentPage = floor((p.x - 320 / 2) / 320) + 1;
        pageControl.currentPage = currentPage;
        
        TJSP *delePlay = [array0 objectAtIndex:currentPage];
        topTitle.text = delePlay.News_title;
    }
}


-(void)pushSearchView{
    SearchViewController *searchViewController = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:searchViewController animated:YES];
    [searchViewController release];
}


-(void)selectSection:(UIButton*)sender{
    NSIndexSet* sections=[NSIndexSet indexSetWithIndex:sender.tag];
    NSNumber* num=[sectionTagArray objectAtIndex:sender.tag];
    int rowCount;
    
    UIImageView *jiantou = (UIImageView *)[sender viewWithTag:999];
    
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:0.3];
    
    if ([num intValue]==1) {
        rowCount=0;
        [jiantou layer].transform = CATransform3DMakeRotation(0, 0, 0, 1);
    }
    else {
        rowCount=1;
        [jiantou layer].transform = CATransform3DMakeRotation(M_PI/2, 0, 0, 1);
    }
    [UIView commitAnimations];
    
    NSNumber* newNum=[NSNumber numberWithInt:rowCount];
    [sectionTagArray replaceObjectAtIndex:sender.tag withObject:newNum];    
    [table reloadSections:sections withRowAnimation:UITableViewRowAnimationNone];
    [table performSelector:@selector(reloadData) withObject:nil afterDelay:0.3];
}

#pragma  mark tableview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [channelArray count]-1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSNumber* rowCount = [sectionTagArray objectAtIndex:section];
    
    if ([rowCount intValue] == 0) {
        return 1;
    }
    else {
        NSInteger subCount = [[array objectAtIndex:section] count];
        return ceil((double)subCount/4.0);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 25;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary* channelDic=[channelArray objectAtIndex:section];
    UIButton* secHeaderView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 25)];
    secHeaderView.tag = section;
    [secHeaderView setBackgroundImage:[UIImage imageNamed:@"lanmubg.png"] forState:UIControlStateNormal];
    [secHeaderView setBackgroundImage:[UIImage imageNamed:@"lanmubg.png"] forState:UIControlStateHighlighted];
    [secHeaderView addTarget:self action:@selector(selectSection:) forControlEvents:UIControlEventTouchUpInside];
    
//    section图标
    NSString* imgurl=[channelDic valueForKey:@"imgUrl"];
    UIImageView* channelIcon=[[UIImageView alloc] initWithFrame:CGRectMake(5, 4, 16, 16)];
    channelIcon.image=[UIImage imageNamed:imgurl];
    [secHeaderView addSubview:channelIcon];
    [channelIcon release];
    
//    section名字
    NSString* channelTit=LS([channelDic valueForKey:@"appName"]);
    UILabel* titLab=[[UILabel alloc] initWithFrame:CGRectMake(27, 0, 200, 25)];
    titLab.textAlignment=UITextAlignmentLeft;
    titLab.backgroundColor=[UIColor clearColor];
    titLab.text=channelTit;
    titLab.font=[UIFont boldSystemFontOfSize:14];
    titLab.textColor=[UIColor whiteColor];
    [secHeaderView addSubview:titLab];
    [titLab release];
  
    //section箭头
    UIImageView *jiantou = [[UIImageView alloc]initWithFrame:CGRectMake(290, 6, 16, 12)];
    jiantou.tag = 999;
    jiantou.image = [UIImage imageNamed:@"jiantou.png"];
    [secHeaderView addSubview:jiantou];
    [jiantou release];
    
    NSNumber* rowCount = [sectionTagArray objectAtIndex:section];
    
    if ([rowCount intValue] == 0) {
        [jiantou layer].transform = CATransform3DMakeRotation(0, 0, 0, 1);
    }
    else {
        [jiantou layer].transform = CATransform3DMakeRotation(M_PI/2, 0, 0, 1);
    }
    

    return [secHeaderView autorelease];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	static NSString* ListIdentifier = @"ListIdentifier";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ListIdentifier];
	
	if (cell == nil)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListIdentifier];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;  //去掉选中时的颜色
	}
	
	for (UIView* subView in [cell.contentView subviews])
	{
		[subView removeFromSuperview];
	}
    
    NSMutableArray *subArray = [array objectAtIndex:indexPath.section];
    
    for (int i=0; i<4; i++) {
        if (4*indexPath.row + i < [subArray count]) {
            UIButton* im = [UIButton buttonWithType:UIButtonTypeCustom];
            im.tag = 1000+1000*indexPath.section + 4*indexPath.row + i;
            [im setBackgroundImage:[UIImage imageNamed:@"dengdai.png"] forState:UIControlStateNormal];
            [im addTarget:self action:@selector(toDetailViewController:) forControlEvents:UIControlEventTouchUpInside];
            im.frame=CGRectMake(10+80*(i%4), 10+100*(i/4), 60, 80);
            [cell.contentView addSubview:im];
            
            TJSP *delePlay = [[array objectAtIndex:indexPath.section] objectAtIndex:4*indexPath.row + i];
            
            if (!delePlay.iconImg && !delePlay.isImageLoading) {
                NSMutableArray *temp = [array objectAtIndex:indexPath.section];
                delePlay.isImageLoading = YES;
                [temp replaceObjectAtIndex:4*indexPath.row + i withObject:delePlay];
                [array replaceObjectAtIndex:indexPath.section withObject:temp];
                
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setValue:delePlay forKey:@"delePlay"];
                [dic setValue:[NSNumber numberWithInt:1000+1000*indexPath.section + 4*indexPath.row + i] forKey:@"indexPath"];
                [self performSelector:@selector(startDownImage:) withObject:dic afterDelay:0.1];
            }
            else if (delePlay.iconImg) {
                [im setBackgroundImage:delePlay.iconImg forState:UIControlStateNormal];
            }
        }
    }
    
	cell.backgroundColor = [UIColor clearColor];
	
	return cell;
}

- (void)startDownImage:(NSDictionary *)dic
{
    TJSP *delePlay = [dic objectForKey:@"delePlay"];
    NSNumber *index= [dic objectForKey:@"indexPath"];
    
    ImageDownloader* imageDown = [[ImageDownloader alloc] init];
    imageDown.imageURL = delePlay.News_pic;
    imageDown.delegate = self;
    imageDown.tag = index.intValue;
    [imageDown startDownload:YES];
    [imageDown release];
}

- (void)appImageDidLoad:(UIImage *)image withTag:(int)tag{
	if (image) {
        if (tag>=20000) {
            UIButton *topImage = (UIButton *)[scroll viewWithTag:tag];
            TJSP *delePlay = [array0 objectAtIndex:tag-20000];
            delePlay.iconImg = image;
            delePlay.isImageLoading = NO;
            [array0 replaceObjectAtIndex:tag-20000 withObject:delePlay];
            [topImage setBackgroundImage:delePlay.iconImg forState:UIControlStateNormal];
        }
        else {
            tag -= 1000;
            NSInteger section = tag / 1000;
            NSInteger row = (tag % 1000)/4;
            NSInteger index = tag % 1000;
            
            UITableViewCell* cell = (UITableViewCell *)[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
            UIButton *tempBtn = (UIButton *)[cell.contentView viewWithTag:tag+1000];
            
            NSMutableArray *temp = [array objectAtIndex:section];
            TJSP *delePlay = [temp objectAtIndex:index];
            delePlay.iconImg = image;
            delePlay.isImageLoading = NO;
            [temp replaceObjectAtIndex:index withObject:delePlay];
            [array replaceObjectAtIndex:section withObject:temp];
            
            [tempBtn setBackgroundImage:delePlay.iconImg forState:UIControlStateNormal];
        }
    }
}

- (void)toDetailViewController:(UIButton *)sender
{
    if (sender.tag>=5000 && sender.tag<6000) {
        PicShowViewController*picshow=[[PicShowViewController alloc] init];
        picshow.imgCount=sender.tag-5000;
        picshow.picListArray=[NSArray arrayWithArray:array5];
        [self.navigationController pushViewController:picshow animated:YES];
        [picshow release];
    }
    else {
        id movie;
        
        if (sender.tag>=20000) {
            movie = [array0 objectAtIndex:sender.tag-20000];
        }
        else {
            NSInteger tag = sender.tag;
            tag -= 1000;
            NSInteger section = tag / 1000;
            NSInteger index = tag % 1000;
            movie = [[array objectAtIndex:section] objectAtIndex:index];
        }
        
        DetailViewController *detailViewController = [[DetailViewController alloc]init];
        detailViewController.type = 1;
        detailViewController.movie = movie;
        [self.navigationController pushViewController:detailViewController animated:YES];
        [detailViewController release];
    }
}

@end
